package me.zhengjie.modules.hanzi.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class ImageDebugUtils {

    private static final String UPLOAD_DIR = "hanzi-debug-images";

    /**
     * 保存用于调试的图片文件.
     * 如果目录不存在，会自动创建.
     * 文件名格式: {汉字}_{时间戳}_user.{后缀}
     *
     * @param imageFile  用户上传的图片文件
     * @param targetChar 目标汉字
     */
    public static void saveImage(MultipartFile imageFile, String targetChar) {
        if (imageFile == null || imageFile.isEmpty()) {
            log.warn("Debug image not saved: image file is null or empty.");
            return;
        }

        try {
            // 确保保存目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                log.info("Created debug image directory: {}", uploadPath.toAbsolutePath());
            }

            // 生成一个唯一的文件名
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS").format(new Date());
            String originalFilename = imageFile.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            // 防止文件名中包含非法字符
            String safeTargetChar = targetChar.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
            String filename = String.format("%s_%s_user%s", safeTargetChar, timestamp, extension);
            
            Path filePath = uploadPath.resolve(filename);

            // 保存文件
            Files.copy(imageFile.getInputStream(), filePath);
            log.info("Debug image saved for character '{}': {}", targetChar, filePath.toAbsolutePath());

        } catch (IOException e) {
            log.error("Failed to save debug image for character '{}'", targetChar, e);
        }
    }
}
